package com.nlscan.qdkit.ui.publico.util;


import java.security.MessageDigest;

public class Encrypt {

    // MD5 + SHA256 处理
    public static String encodeWithHashAndMd5(String input) {
        return new String(getEncode(Encrypt.sha256(input)));
    }

    //SHA256 处理
    public static String sha256(String data) {
        String ans = "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(data.getBytes("utf-8"));
            byte[] temp = messageDigest.digest();
            ans = DataUtil.bytesToHex(temp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ans;
    }

    //获取MD5摘要 为32位16进制字符串
    private static String getMD5(String message) {
        String md5str = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] input = message.getBytes();
            byte[] buff = md.digest(input);
            md5str = bytesToHex(buff);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return md5str;
    }

    private static byte[] getEncode(String message) {
        byte[] temp = new byte[0];
        if (message != null && !message.equals("")) {
            temp = compress(getMD5(message));
        }
        return temp;
    }

    //将32位字符串压缩为8位字符串
    private static byte[] compress(String md5) {
        int[] input = hexToInts(md5);
        byte[] output = new byte[8];
        for (int i = 0; i <= 7; i++) {
            assert input != null;
            output[i] = (byte) ((input[2 * i] + input[2 * i + 1]) % 62);
            if ((output[i] >= 0) && (output[i] <= 9)) {
                output[i] += 48;
            } else {
                if ((output[i] >= 10) && (output[i] <= 35)) {
                    output[i] += 55;
                } else {
                    output[i] += 61;
                }
            }
        }
        return output;
    }

    //将16进制字符串转化为int数组 取2位拼接在一块
    private static int[] hexToInts(String str) {
        int strSize = str.length();
        if (strSize % 2 == 1) {
            return null;
        }
        char[] temp = new char[strSize];
        int[] output = new int[strSize / 2];

        str.getChars(0, strSize, temp, 0);
        for (int i = 0; i < strSize / 2; i++) {
            output[i] = Integer.parseInt(String.valueOf(temp[i * 2]) + String.valueOf(temp[i * 2 + 1]), 16);
        }
        return output;
    }

    //将byte数组转换为16进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder md5str = new StringBuilder();
        int digital;
        for (byte aByte : bytes) {
            digital = aByte;

            if (digital < 0) {
                digital += 256;
            }
            if (digital < 16) {
                md5str.append("0");
            }
            md5str.append(Integer.toHexString(digital));
        }
        return md5str.toString().toUpperCase();
    }
}
